/**
 * t自定义受众管理
 */
define(['../../common/service','../../common/utils','upload'],function(http){
    //业务处理
    var Audience = function () {
        this.step = 1;
        this.data1 = [
            { id: 'CUSTOMER_ROSTER', text: I18N.getText('customAudience','customerList') },
            { id: '1', text: I18N.getText('customAudience','webSiteNoSupprot'),disabled:"disabled"},
            { id: 2, text: I18N.getText('customAudience','AppAcivieNoSupprot'),disabled:"disabled" }
        ],this.data2 = [
            { id: 'APP_USER', text: I18N.getText('customAudience','AppAcivieUser') },
            { id: 'EMAIL', text: I18N.getText('customAudience','EmailNoSupport') ,disabled:"disabled"},
            { id: 'PHONE', text:I18N.getText('customAudience','PhoneNoSupport') ,disabled:"disabled"},
            { id: 'MOBILE_ADVERTISER_IDS', text: I18N.getText('customAudience','mobileAdIdsNoSupport')  ,disabled:"disabled"}
        ]//记录创建的步数
    }
    Audience.prototype = $.extend(Audience.prototype, {
        _initSearchEvent: function () {
            var _this = this;
            //查询btn
            $('#au-search-btn').unbind('click').on('click',function(){
                _this._query.cPage = 1;
                _this.getList();
            });
        },
        init: function () {
            var _this = this;
            _this._initTabs();
            _this._initSelect();
            _this._initSearchEvent();
            //列表管理
            $('table[list-manager="listAdwordsByTags"]').listManager('init', {
                setTopVal:231//调整吸顶的高度,需要减去这个高度
                ,scrollDOM:$('.fmp-article')//监听滚动条
                ,supportAjaxPage: true
                ,isDevelopMode   : false		//是否为开发模式，为true时将打印事件日志
                ,basePath		: ''			//当前基本路径[用于加载资源文件]
                ,useDefaultStyle: false		//是否使用默认的table样式
                ,animateTime	:300		//动画效果延时
                ,minNum:40					//宽度所允许的最小值
                ,supportAdjust	: true		//是否支持宽度调整
                ,supportDrag	: false 		//是否支持拖拽换位
                ,supportConfig	: false 		//是否支持配置列表功能[操作列是否可见]
                ,supportSetTop	: true		//是否支持表头置顶
                ,autoLoadCss	: false
                ,pageCallback: function(query){
                    $.extend(_this._query, query);
                    _this.getList();
                }
            }, function(query){
                _this._query = {
                    pSize: query.pSize,
                    cPage:1
                };
                _this.getList();			//获取列表数据
            });
            //绑定 创建按钮
            _this._bindDialogClick();
            //_this._initSaveFileUploader();
            //_this._initUpdateFileUploader();
            _this._initCheckRedio();
            _this._bindRetry();
        }
        ,getList:function(){
            var _this = this;
            var loadingArea = $('#au-grid');
            Kit.loading.show(loadingArea);
            var par = _this._query;
            par.audienceType =  $(".custom-list-array").val();
            par.importedType = $(".app-list-array").val();
            http.do('/customaudiencetemplate/list',{param:JSON.stringify(par)},'POST').then(function(res){
                var data = res.data;
                //操作DOM节点更换数据
                var _table = $('table[list-manager="listAdwordsByTags"]'),
                    _tbody = $('#au-grid', _table).empty(),
                    tmpHtml = '',
                    _list = data.customaudiences;
                if(_list.length == 0){
                    tmpHtml += '<tr><td colspan="7" style="font-size: 34px;color: #777;height: 211px;">'
                        + I18N.getText('customAudience','noUploadMsg')+'</td></tr>';
                    _tbody.html(tmpHtml);
                }
                if(data.paginator.length == 0){
                    console.log('分页数据为空，已返回');
                    return false;
                }
                if(!_list || _list.length == 0){
                    _table.listManager([{'resetTd': false, 'resetPageData': data.paginator}]);
                    console.log('列表为空，已返回');
                    return false;
                }
                for(var i=0; i< _list.length; i++){
                    tmpHtml += '<tr data-id="'+_list[i].id+'">'
                        + '<td title="'+_list[i].name+'" class="text-left" style="font-size:15px">'
                        + '<div><a href="javascript:void(0)" class="td-a-budget modifyClass"><i class="fa fa-edit"></i></a><span class="keywordDiv">'
                        + _list[i].name
                        + '</span></div><label class="input hide"><input class="input-budget" type="text" size="8" value="'+_list[i].name+'" name="modify-name" maxlength="100"></label>'
                        + '</td>'
                        + '<td width="100" class="text-center">'
                        + _list[i].appSource
                        + '</td>'
                        + '<td width="100" class="text-center">'
                        + _list[i].creator
                        + '</td>'
                        + '<td width="100" class="text-center">'
                        + (_list[i].approximateCount==0 ? '--': (_list[i].approximateCount)+ '人')
                        + '</td>'
                        + '<td width="100" class="text-center">'
                        + new Date(_list[i].timeUpdated).format('yyyy-MM-dd hh:mm:ss')
                        + '</td>'
                        + '<td width="100" class="text-center">'
                        + _list[i].availableAccountNum + '/ '+ + _list[i].accountNum
                        + '</td>'
                        + '<td width="100" class="text-center">'
                        + '<a href="javascript:void(0);" name="update">'
                        + '<span class="glyphicon glyphicon-refresh"></span>'
                        +'</a> | <a name="delete" href="javascript:void(0);">'
                        + '<span class="glyphicon glyphicon-trash"></span>'
                        + '</a>'
                        + '<input type="hidden" name="templateId" value="'+_list[i].id+'"></td>'
                        + '</tr>';
                }
                _tbody.html(tmpHtml);
                Kit.loading.hide(loadingArea);
                _table.listManager([{'resetTd':false, 'resetPageData': data.paginator}]);
                //绑定列表的时间
                _this._bindTableColumnEvent();
            });
        }
        ,_bindDialogClick:function(){
            var _this = this;
            // init dialog
            $("#au-create-btn").unbind('click').bind('click',function(){
                _this._initDialog('create');
                $('#create-au-dialog').modal({backdrop: 'static', keyboard: false});
            });
            //step 1
            $("#create-au-dialog div[name='manual-btn']").unbind('click').bind('click',function(){
                $("#create-au-dialog div[name='step1']").hide();
                $("#create-au-dialog div[name='step2']").show();
                //显示返回btn
                $(".cancel-btn").hide();
                $(".step3-back-btn").show();
                _this.step++;
            });
            //step 2
            $("#create-au-dialog div[name='user-list-btn']").unbind('click').bind('click',function(){
                $("#create-au-dialog div[name='step2']").hide();
                $("#create-au-dialog div[name='step3']").show();
                $(".data-type").select2({
                    minimumResultsForSearch: -1,
                    data: _this.data2
                });
                $(".step3-btn").show();
                _this.step++;
                //获取seelct应用列表
                http.do("/connectionobjects/searchOwnerConnObj",{param:''},'POST').then(function (res){
                    var data = res.data;
                    var tmpHtml = '';
                    $.each(data, function(index, dict){
                        tmpHtml += '<option img="'+(dict.iconUrl || '')+ '" value="'+(dict.fbConnectionObjectId || '')+'">'
                            + (dict.fbConnectionObjectId|| '') + '&nbsp;(' + (dict.name || '') + ')</span>';
                        + '</option>'
                    });
                    $(".app-no").html(tmpHtml);
                    var $eventSelect = $(".app-no").select2({
                        templateResult: formatState,
                        templateSelection:formatState,
                        escapeMarkup: function(m) { return m; }
                    });
                    function formatState(state) {
                        var t = $(state.element).attr("img");
                        if(!t){
                            t = '';
                        }
                        var $state =$(
                            '<span><img src="'+t +'" class="img-flag" width="20" height="20" /> '+state.text+ '</span>');
                        return $state;
                    };
                });

                //初始化上传save组件
                _this._initSaveFileUploader();
            });
            //dialog 返回按钮
            $("#create-au-dialog .step3-back-btn").unbind('click').bind('click',function(){
                switch(_this.step){
                    case 1 :
                        // 关闭dialog  //替换为取消按钮
                        //_this._closeDialog($("#create-au-dialog"));
                        break;
                    case 2 :
                        $("#create-au-dialog div[name='step2']").hide();
                        $("#create-au-dialog div[name='step1']").show();
                        //显示返回btn
                        $(".step3-back-btn").hide();
                        $(".cancel-btn").show();
                        _this.step--;
                        break;
                    case 3 :
                        $("#create-au-dialog div[name='step3']").hide();
                        $(".step3-btn").hide();
                        $(".cancel-btn").hide();
                        $("#create-au-dialog div[name='step2']").show();
                        _this.step--;
                        break;
                    default:
                        break;
                }
            })
            // 上传按钮
            $(".step3-btn").unbind('click').bind('click',function(){
                var obj = this;
                if(!_this._ckeckAddEmptyCondition($('#create-au-dialog'))){
                    Kit.alert2(I18N.getText('customAudience','uploadNullMsg'));
                    return false;
                }
                if(!_this._checkUploadCondition()){
                    var html = $("div[name='step3'] footer[name='warn']").html();
                    Kit.alert2(html);
                    return false;
                };
                //判断应用
                if(!_this._checkUploadAppCondition()){
                    Kit.alert2(I18N.getText('customAudience','selectApp'));
                    return false;
                }
                //按钮置灰
                _this._disabledBtn($(this),false);
                if($('input[name="add-style-redio"]:checked').val() == 0){
                    // add file
                    //$('div[name="fine-uploader-manual-trigger"]').fineUploader('uploadStoredFiles');
                    //组件已经绑定了提交事件
                }else{
                    // paste file
                    var par = {
                        importedType:'APP_USER',
                        content : $("textarea[name='addContent']").val(),
                        deliverType:'PASTE_COPY',
                        appIds:$("select[name='appIds']").val(),
                        audienceType:'CUSTOMER_ROSTER'
                    }
                    http.do('/customaudiencetemplate/save',par,'POST').then(function(res){
                        if(res.flag == "success"){
                            _this._saveFileUploadStep4(1,res.data.audienceTemplateId,res.data.count,res.data.audienceName);
                        }else{
                            Kit.alert2(res.msg);
                            _this._disabledBtn($(obj),true);
                        }
                    },function(){
                        Kit.alert2(I18N.getText('customAudience','uploadError'));
                        _this._disabledBtn($(obj),true);
                    });
                }
            });
            //更新自定义受众
            $(".update-btn").unbind('click').bind('click',function() {
                var obj = this;
                if(!_this._ckeckUpdateEmptyCondition($('#update-au-dialog'))){
                    Kit.alert2(I18N.getText('customAudience','uploadNullMsg'));
                    return false;
                }
                if(!_this._checkUploadCondition()){
                    var html = $("div[name='step3'] footer[name='warn']").html();
                    Kit.alert2(html);
                    return false;
                };
                _this._disabledBtn($(this),false);
                if($('input[name="update-style-redio"]:checked').val() == 0){
                    // add file
                    $("#templateId").val($('#update-au-dialog').data("id"));
                    //$('div[name="update-fileupload-trigger"]').fineUploader('uploadStoredFiles');
                }else{
                    // paste file
                    var par = {
                        templateId:$('#update-au-dialog').data("id"),
                        importedType:'APP_USER',
                        content : $("#update-au-dialog textarea[name='updateContent']").val(),
                        deliverType:'PASTE_COPY',
                        audienceType:'CUSTOMER_ROSTER',
                        editType:$('input[name="editType"]:checked').val()
                    }
                    http.do('/customaudiencetemplate/update',par,'POST').then(function(res){
                        if(res.flag == "success"){
                            Kit.alert_success(I18N.getText('customAudience','updateSucceed'));
                            _this._closeDialog($("#update-au-dialog"));
                            _this.getList();
                        }else{
                            Kit.alert2(res.msg);
                            _this._disabledBtn($(obj),true);
                        }
                    },function(){
                        Kit.alert2(I18N.getText('customAudience','updateFail'));
                        _this._disabledBtn($(obj),true);
                    });
                }
            });

            //删除自定义受众
            $(".delete-btn").unbind('click').bind('click',function(){
                var loadingArea = $("#delete-au-dialog");
                Kit.loading.show(loadingArea);
                var obj = this;
                _this._disabledBtn($(obj),false);
                var _ids = [];
                _ids.push(parseInt($('#delete-au-dialog').data("id")));
                var par = {
                    ids : _ids,
                    flag:$("input[name='delete-radio']:checked").val()
                }
                http.do('/customaudiencetemplate/del',{param:JSON.stringify(par)},'POST').then(function(res){
                    Kit.loading.hide(loadingArea);
                    _this._closeDialog($("#delete-au-dialog"));
                    if(res.flag == "success"){
                        Kit.alert_success(I18N.getText('customAudience','deleteSucceed'));
                    }else{
                        Kit.alert2(res.msg);
                    }
                    _this._disabledBtn($(obj),true);
                    _this.getList();
                });
            });
        }
        ,_initSelect:function(){
            var _this = this;
            $(".custom-list-array").select2({
                minimumResultsForSearch: -1,
                data: _this.data1
            })
            $(".app-list-array").select2({
                minimumResultsForSearch: -1,
                data: _this.data2
            })
        }
        ,_initSaveFileUploader:function(){
            var _this = this;
            $('div[name="fine-uploader-manual-trigger"]').empty();
            $('div[name="fine-uploader-manual-trigger"]').fileupload({
                //以下是上传处理的ajax
                //所有的参数参照jquery
                form:$("#addFileForm"),
                text: {
                    upload: {
                        uploading: I18N.getText('customAudience','uploading'),
                        success: I18N.getText('customAudience','success'),
                        tips: I18N.getText('customAudience','tips'),
                        linkword: I18N.getText('customAudience','linkword'),
                        descUploading: I18N.getText('customAudience','descUploading'),
                        descButton:I18N.getText('customAudience','descButton'),
                        agButton: I18N.getText('customAudience','agButton')
                    },
                    error: {
                        type: I18N.getText('customAudience','type'),
                        size:I18N.getText('customAudience','size'),
                        number:I18N.getText('customAudience','number'),
                        none:I18N.getText('customAudience','none'),
                        allowSize: I18N.getText('customAudience','allowSize')
                    }
                },
                ajax:{
                    url:'http://walle.clientgear.com/customaudiencetemplate/save',
                    success:function(res, status, xhr){
                        if(res.flag == "success"){
                            //上传成功！
                            var id = res.data.audienceTemplateId,count = res.data.count,name = res.data.audienceName;
                            _this._saveFileUploadStep4(0,id,count,name);
                        }else{
                            Kit.alert2(res.msg);
                        }
                    }
                },
                name: 'qqfile',   //上传拖拽区域的字段   //起这个名字的原因是因为之前用了一个qqfileupload的组件，为了和后台老的代码一致
                type: /application\/vnd.ms-excel|text\/comma-separated-values|text\/plain/,  //上传文件的类型
                width: 420,     //上传拖拽区域宽度
                height: 170,    //上传拖拽区域高度
                size: 10485760, //默认上传大小不超过10M
                //区域的预览模板
                //必须包含upload-wrapper、upload-content、upload-desc、upload-preview、upload-mask 这几个class的dom
                //预览的模板，如果没有指定，则根据type确定，
                //如果指定了一个字符串,占位符{{src}}预览文件的url
                //如果指定了一个函数，则会有两个参数一个是文件的File对象，一个是File对象对应的预览url
                button:".step3-btn",
                previewTpl: function(file, src){
                    return '<div style="margin-left: 20px;">' +
                        '<p><img style="width: 40px;height: 40px;margin-top: 5px;margin-right: 5px;" ' +
                        'src="imgs/text.png"/>' + file.name + '</p>' +
                        '<p class="small">'+ I18N.getText('customAudience','fileSize') + ': '
                        + file.size + 'B</p>' +
                        '<p class="small">' + I18N.getText('customAudience','fileUploadTime') + ': '
                    + new Date(file.lastModified).toLocaleString()  + '</p>'
                        '</div>';
                }
            });
            $('.upload-button-other').click(function(){
                _this._disabledBtn($(".step3-btn"),true);
            });
        }
        ,_initUpdateFileUploader:function(){
            var _this = this;
            $('div[name="update-fileupload-trigger"]').empty();
            $('div[name="update-fileupload-trigger"]').fileupload({
                //以下是上传处理的ajax
                //所有的参数参照jquery
                form:$("#updateForm"),
                text: {
                    upload: {
                        uploading: I18N.getText('customAudience','uploading'),
                        success: I18N.getText('customAudience','success'),
                        tips: I18N.getText('customAudience','tips'),
                        linkword: I18N.getText('customAudience','linkword'),
                        descUploading: I18N.getText('customAudience','descUploading'),
                        descButton:I18N.getText('customAudience','descButton'),
                        agButton: I18N.getText('customAudience','agButton')
                    },
                    error: {
                        type: I18N.getText('customAudience','type'),
                        size:I18N.getText('customAudience','size'),
                        number:I18N.getText('customAudience','number'),
                        none:I18N.getText('customAudience','none'),
                        allowSize: I18N.getText('customAudience','allowSize')
                    }
                },
                ajax:{
                    url:'http://walle.clientgear.com/customaudiencetemplate/update',
                    success:function(res){
                        if(res.flag == "success"){
                            //更新成功！
                            _this._closeDialog($("#update-au-dialog"));
                            Kit.alert_success(I18N.getText('customAudience','updateSucceed'));
                            _this.getList();
                        }else{
                            Kit.alert2(res.msg);
                        }
                    }
                },
                name: 'qqfile',   //上传拖拽区域的字段   //起这个名字的原因是因为之前用了一个qqfileupload的组件，为了和后台老的代码一致
                type: /application\/vnd.ms-excel|text\/comma-separated-values|text\/plain/,  //上传文件的类型
                width: 420,     //上传拖拽区域宽度
                height: 170,    //上传拖拽区域高度
                size: 10485760, //默认上传大小不超过10M
                //区域的预览模板
                //必须包含upload-wrapper、upload-content、upload-desc、upload-preview、upload-mask 这几个class的dom
                //预览的模板，如果没有指定，则根据type确定，
                //如果指定了一个字符串,占位符{{src}}预览文件的url
                //如果指定了一个函数，则会有两个参数一个是文件的File对象，一个是File对象对应的预览url
                button:".update-btn",
                previewTpl: function(file, src){
                    return '<div style="margin-left: 20px;">' +
                        '<p><img style="width: 40px;height: 40px;margin-top: 5px;margin-right: 5px;" ' +
                        'src="imgs/text.png"/>' + file.name + '</p>' +
                        '<p class="small">'+ I18N.getText('customAudience','fileSize') + ': '
                        + file.size + 'B</p>' +
                        '<p class="small">' + I18N.getText('customAudience','fileUploadTime') + ': '
                        + new Date(file.lastModified).toLocaleString()  + '</p>'
                    '</div>';
                }
            });
            $('.upload-button-other').click(function(){
                _this._disabledBtn($(".update-btn"),true);
            });
        }
        ,_initCheckRedio:function(){
            var _this = this;
            $("div[name='step3']").find("input[name='add-style-redio']").unbind('click').bind('click',function(){
                if($(this).val() == 0){
                    $("div[name='pastePanel']").hide();
                    $("div[name='addPanel").show();
                }else{
                    $("div[name='addPanel").hide();
                    $("div[name='pastePanel").show();
                }
            });
            $("div[name='step3']").find("input[name='update-style-redio']").unbind('click').bind('click',function(){
                if($(this).val() == 0){
                    $("div[name='pastePanel']").hide();
                    $("div[name='addPanel").show();
                }else{
                    $("div[name='addPanel").hide();
                    $("div[name='pastePanel").show();
                }
            });
        }
        //,cleanWarnHtml:function(){
        //    $("#create-au-dialog div[name='step3'] footer[name='warn']").html("");
        //}
        ,_bindTableColumnEvent:function(){
            var _this = this;
            //绑定 输入框
            //弹出层
            $("#au-grid tr").unbind('click').bind('click',function(e){
                if(e.target.nodeName != 'TD' && e.target.nodeName != 'TR' && e.target.nodeName != 'SPAN'){
                    return false;
                }
                if(e.target.className.indexOf("glyphicon",0) != -1){
                    //如果点击的是更新或者删除按钮。
                    return false;
                }
                _this._initCollapseTable($(this));
            });
            $(".modifyClass").unbind('click').bind('click',function (e) {
                $(this).parent("div").addClass('hide');
                $(this).parent("div").next().removeClass('hide');
            });
            $("input[name='modify-name']").focusout(function () {
                var str = $(this).val();
                $(this).parent().addClass('hide');
                $(this).parent().prev().removeClass('hide');
                $(this).parent().prev().find("span").html(str);
                //请求后台更新名称
                var par = {
                    templateId:$(this).parents('tr').find("input[name='templateId']").val(),
                    audienceName:$(this).val()
                }
                http.do('/customaudiencetemplate/updateName',{param:JSON.stringify(par)},'POST').then(function(res) {
                    if(res.flag == "success"){
                        console.log('update name succeed');
                    }else{
                        Kit.alert2(res.msg);
                    }
                });
            });
            //更新
            $("a[name='update']").unbind('click').bind('click',function(){
                var templateId = $(this).nextAll("input").val();
                $('#update-au-dialog').data("id",templateId);
                _this._initDialog("update");
                $('#update-au-dialog').modal({backdrop: 'static', keyboard: false});
            });
            //删除
            $("a[name='delete']").unbind('click').bind('click',function(){
                var templateId = $(this).next("input").val();
                var name = $(this).parent().parent('tr').find("input[name=modify-name]").val();
                $('#delete-au-dialog').data("id",templateId);
                $('#delete-au-dialog span[name=del-name]').each(function(i){
                    $(this).html(name);
                });
                $('#delete-au-dialog').modal({backdrop: 'static', keyboard: false});
            });

        }
        ,_saveFileUploadStep4:function(flag,id,count,name){
            var _this = this;
            $(".step3-btn").hide();
            $(".step3-back-btn").hide();
            $("#create-au-dialog div[name='step3']").hide();
            $(".step4-btn").show();
            $("#create-au-dialog div[name='step4']").show();
            $('.audience-update-users').html(count);

            if(flag == 0){
                $("div[name='step4']").find("input[type='text']").val(name);
            }
            $(".step4-btn").unbind('click').bind('click',function(e){
                //判断是否为空
                var au_name = $("div[name='step4']").find("input[type='text']").val();
                if(au_name == ""){
                    Kit.alert2(I18N.getText('customAudience','inputAudienceName'));
                    return false;
                }
                //if(au_name.length > 100){
                //    Kit.alert2("受众名称长度不能超过100");
                //    return false;
                //}
                var namePar = {
                    templateId:id,
                    audienceName:$("#create-au-dialog div[name='step4'] input").val()
                }
                http.do('/customaudiencetemplate/updateName',{param:JSON.stringify(namePar)},'POST').then(function(res) {
                    if(res.flag == "success"){
                        console.log('自定义受众名称上传成功！');
                        //关闭dialog，刷新页面
                        _this._closeDialog($("#create-au-dialog"));
                        _this.getList();
                    }else{
                        Kit.alert2(I18N.getText('customAudience','audienceNameFail'));
                    }
                });
            });
        }
        ,_initDialog:function(name){
            var _this = this;
            //1、回退到原始step1界面
            //2、初始化所有参数
            if(name == "create"){
                $("#create-au-dialog div[name='step2']").hide();
                $("#create-au-dialog div[name='step3']").hide();
                $("#create-au-dialog div[name='step4']").hide();
                $("#create-au-dialog div[name='step1']").show();
                //初始化所有页面参数
                //step3
                $("select[name='appIds']").val('-1').trigger('change');
                $('.qq-upload-cancel').click();
                $("textarea[name='addContent']").val('');
                $("div[name='step3']").find("input[name='add-style-redio']").eq(0).click();
                //step4
                $("div[name='step4']").find("input[type='text']").val('');
                //btn
                $(".step3-btn").hide();
                $(".step4-btn").hide();
                $(".step3-back-btn").hide();
                $(".cancel-btn").show();
                _this.step =1;
                //初始化btn
                _this._disabledBtn($(".step3-btn"),true);
            }else if(name == "update"){
                $('input[name="editType"]').eq(0).click();
                _this._initUpdateFileUploader();
                $("textarea[name='updateContent']").val('');
                $('input[name="update-style-redio"]').eq(0).click();
                _this._disabledBtn($(".update-btn"),true);
            }else{
                //delete
                $('input[name="delete-radio"]').eq(0).click();
            }
            $("div[name='step3'] footer[name='warn']").html('');
        }
        ,_closeDialog:function($dom){
            $dom.modal('hide');
        }
        ,_initCollapseTable:function($Dom){
            var _this = this;
            if ($Dom.next("#ad-account-status").get(0)) {
                //已渲染
                $("#ad-account-status").remove();
                return;
            } else {
                $("#ad-account-status").remove();
            }
            var html = '<tr id="ad-account-status"><td colspan="7" name="colspanTd"><div name="collapseTable">' +
                '<table class="table table-bordered table-hover" style="visibility: visible;background-color: #fff;"><thead>' +
                '<th width="30%">'+I18N.getText('customAudience','account')+'</th><th width="70%">'+I18N.getText('customAudience','status')+'</th></thead><tbody>' +
                '</tbody></table>'+
                '</div></td></tr>';
            $Dom.after(html);
            var _par = {id:$Dom.find("input[name='templateId']").val()};
            http.do('/customaudiencetemplate/customAudienceItemList',{param:JSON.stringify(_par)},'POST').then(function(res){
                if(res.flag == "success"){
                    var _data = res.data.result;
                    var temp = "";
                    for(var i = 0;i<_data.length;i++){
                        //temp += "<tr><td>"+ _data[i].fbAccountName +"</td><td>";
                        //if(_data[i].requestQueueStatus == 0){
                        //    temp +=I18N.getText('customAudience','uploading')+"</td></tr>";
                        //}else if(_data[i].requestQueueStatus == 1 &&　_data[i].deliveryStatusCode == 200){
                        //    temp +=I18N.getText('customAudience','createSucceed')+"</td></tr>";
                        //}else if(_data[i].requestQueueStatus == 1 &&　_data[i].deliveryStatusCode == -1){
                        //    temp +=I18N.getText('customAudience','uploading')+"</td></tr>";
                        //}else{
                        //    temp +="<span style='color: red'>"+I18N.getText('customAudience','uploadError')+"[<span>" + _data[i].deliveryStatusDescription +"</span>]</span></td></tr>";
                        //}
                        temp +=I18N.getText('customAudience','uploading')+ "<tr><td>" + _data[i].fbAccountName
                        //没有fbCustomAudienceId的可以重试
                        if(_data[i].customAudienceId == -1)
                        {
                            temp += '&nbsp;&nbsp;<span class="retryAudience" style="cursor:pointer;color:#337ab7" tmplId="'+ _par.id +'" fbAccountId="' + (_data[i].fbAccountId || '') + '" customAudienceDbId="' + (_data[i].id || '') + '">'+I18N.getText('customAudience','retry')+'</span>';
                        }
                        temp += "</td><td>";
                        console.log('requestQueueStatus>'+_data[i].requestQueueStatus + ';operationStatusCode>'+_data[i].operationStatusCode+';deliveryStatusCode>'+_data[i].deliveryStatusCode)
                        if (_data[i].requestQueueStatus == 0 || (_data[i].requestQueueStatus == 1 && _data[i].operationStatusCode == -1 && _data[i].deliveryStatusCode == -1)) {
                            temp += I18N.getText('lookalikeAudience','uploading');
                        } else if (_data[i].requestQueueStatus == 1 && _data[i].operationStatusCode == 200 && _data[i].deliveryStatusCode == 200) {
                            temp += I18N.getText('customAudience','createSucceed');
                        }  else {
                            if(_data[i].operationStatusCode == 200 || _data[i].operationStatusCode == -1){
                                temp += "<span style='color: red'>"+"[<span>" + _data[i].deliveryStatusDescription + "</span>]</span>";
                            } else if(_data[i].operationStatusCode == 300) {
                                temp += I18N.getText('customAudience','updatingAudience');
                            } else {
                                temp += "<span style='color: red'>"+I18N.getText('lookalikeAudience','uploadError')+"[<span>" + _data[i].deliveryStatusDescription + "</span>]</span>";
                            }
                        }

                        temp += '</td></tr>';
                    }
                    //var html = '<tr id="ad-account-status"><td colspan="7" name="colspanTd"><div name="collapseTable">' +
                    //    '<table class="table table-bordered table-hover"><thead>' +
                    //    '<th width="30%">账户</th><th width="70%">状态</th></thead><tbody>' + temp +
                    //    '</tbody></table>'+
                    //    '</div></td></tr>';
                    $('#ad-account-status').find('tbody').append(temp);
                }else{
                    Kit.alert2(I18N.getText('customAudience','queryFail'));
                }
            });

        }
        ,_bindRetry: function(){
            //重试
            $('[list-manager="listAdwordsByTags"]').off('click', '.retryAudience');
            $('[list-manager="listAdwordsByTags"]').on('click', '.retryAudience',function(){
                var templateId = $(this).attr('tmplId');
                var fbAccountId = $(this).attr('fbAccountId');
                var customAudienceDbId = $(this).attr('customAudienceDbId');
                var _par = {tmplId: templateId, fbAccountId: fbAccountId, customAudienceDbId: customAudienceDbId};
                http.do('/customaudiencetemplate/retryCustomAudience',{param:JSON.stringify(_par)},'POST').then(function(res){
                    if(res.flag == "success"){
                        Kit.alert_success(I18N.getText('customAudience','retrySucceed'));
                    }else{
                        Kit.alert2(I18N.getText('customAudience','retryFail'));
                    }
                });
            });
        }
        ,_disabledBtn:function($Dom,flag){
            if(flag){
                $Dom.removeAttr("disabled")
            }else{
                $Dom.attr("disabled","disabled");
            }
        }
        ,_ckeckAddEmptyCondition:function($Dom){
            //if($Dom.find('input[name="add-style-redio"]:checked').val() == 0 && $Dom.find(".qq-upload-list li").length == 0){
            //    return false;
            //}else
            if($Dom.find('input[name="add-style-redio"]:checked').val() == 1 && $Dom.find("textarea").val() == ''){
                console.log("粘贴框为空");
                return false;
            }else{
                return true;
            }
        }
        ,_ckeckUpdateEmptyCondition:function($Dom){
            //console.log($Dom);
            //if($Dom.find('input[name="update-style-redio"]:checked').val() == 0 && $Dom.find(".qq-upload-list li").length == 0){
            //    return false;
            //}else
            if($Dom.find('input[name="update-style-redio"]:checked').val() == 1 && $Dom.find("textarea").val() == ''){
                console.log("粘贴框为空");
                return false;
            }else{
                return true;
            }
        }
        ,_checkUploadCondition:function(){
            var html = $("div[name='step3'] footer[name='warn']").html();
            if(html != ""){
                //格式不正确
                return false;
            }else{
                return true;
            }

        }
        ,_checkUploadAppCondition:function(){
            var appId = $("select[name='appIds']").val();
            if(appId == "-1"){
                //格式不正确
                return false;
            }else{
                return true;
            }
        }
        ,dispose: function () {
        }
        ,_initTabs:function(){
            $("div.ndp-tab-wrapper[name=plain-tab]").tabs({
                list:[I18N.getText('customAudience','customAudience'),I18N.getText('customAudience','likeAudience')]
            }).on("TAB_CHANGE",function(e){//点击其中的一个tab发生事件
                switch (e.originalEvent.data.index){
                    case 0:
                        window.location.hash = "#!customAudience";
                        break;
                    case 1:window.location.hash = "#!lookalikeAudience";
                        break;
                }
            }).val(0);//设置选中的tab 索引，默认0
        }
    })
    return new Audience();
});
